<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" fullscreen
    center append-to-body>
    <el-form class="verify-form" :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-row>
        <el-col :span="8" v-if="dataForm.id">
          <el-form-item label="发票号" prop="billId">
            <el-input v-model="dataForm.billId" placeholder="发票号" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="创建时间" prop="createTime">
            <el-input v-model="dataForm.createTime" placeholder="创建时间" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制造商">
            <el-input v-model="dataForm.supplyName" readonly>
              <el-button slot="append" @click="supplySearchHandle" :disabled="dataForm.id!=0">选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="创建部门">
            <el-input v-model="dataForm.createDeptName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="创建人" prop="createUserName">
            <el-input v-model="dataForm.createUserName" placeholder="创建人" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发票类型" prop="type">
            <el-select v-model="dataForm.type" placeholder="请选择套餐类型" :disabled="dataForm.id!=0">
              <el-option label="采购普通发票" value="1"></el-option>
              <el-option label="采购增值税发票" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="订单备注" prop="memo">
        <el-input type="textarea" v-model="dataForm.memo" placeholder="订单备注"></el-input>
      </el-form-item>

      <el-tabs type="border-card">
        <el-divider content-position="left">单据信息</el-divider>
        <el-row>
          <el-button type="primary" icon="el-icon-plus" @click.prevent="addRow()">选择单据</el-button>
          <el-button type="primary" icon="el-icon-delete" @click.prevent="delData()">删除</el-button>
        </el-row>
        <div class="avue-crud">
          <el-table :data="dataForm.detailList" border @selection-change="handleSelectionChange" show-summary
            :summary-method="getSummaries">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="invoiceTicket" header-align="center" align="center" label="来票号">
              <template slot-scope="scope">
                <el-input v-model="scope.row.invoiceTicket" style="width: 100px;"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="costPrice" header-align="center" align="center" label="成本合计">
              <template slot-scope="scope">
                <el-input v-model="scope.row.costPrice" style="width: 100px;"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="taxPrice" header-align="center" align="center" label="税额合计">
              <template slot-scope="scope">
                <el-input v-model="scope.row.taxPrice" style="width: 100px;"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="allPrice" header-align="center" align="center" label="价税合计">
              <template slot-scope="scope">
                <el-input v-model="scope.row.allPrice" style="width: 100px;"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tabs>




      <!-- 弹窗，查询制造商 -->
      <search-supply v-if="supplyVisible" ref="supplyDialog" @refreshData="getSupplyData"></search-supply>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>确定</el-button>
      <el-switch v-model="dataForm.status" active-text="保存并审核" inactive-value="0" active-value="1" style="margin-left: 15px;"></el-switch>
    </span>
  </el-dialog>
</template>

<script>
  import {
    getObj,
    addObj,
    putObj
  } from '@/api/eims/invoice'

  import SearchSupply from '@/components/business/SearchSupply'

  import { mapGetters } from 'vuex'

  import { getDeptInfo } from '@/api/admin/dept'

  export default {
    data() {
      return {
        ischeck: false,
        visible: false,
        supplyVisible: false,
        dataForm: {
          id: 0,
          billId: '',
          type: '',
          supplyId: '',
          supplyName: '',
          status: '',
          memo: '',
          status: '0',
          createDeptId: '',
          createDeptName: '',
          createTime: '',
          createUser: '',
          createUserName: '',
          detailList: [],
        },
        deptOptions: [],
        dataRule: {
          type: [{
            required: true,
            message: '发票类型(1-普通发票,2-增值税发票)不能为空',
            trigger: 'blur'
          }],
          supplyName: [{
            required: true,
            message: '制造商名称不能为空',
            trigger: 'blur'
          }],
        }
      }
    },
    created() {
      this.timeFormate(new Date());
      this.getDeptList();
    },
    components: {
      SearchSupply
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    methods: {
      init(id) {
        this.dataForm.id = id || 0
        this.visible = true
        if (!this.dataForm.id) {
          for (var key in this.dataForm) {
            if (key != 'createTime') {
              this.dataForm[key] = ''
            }
          }
          this.dataForm.detailList = []
          this.dataForm.createUserName = this.userInfo.realName
          this.dataForm.createDeptId = this.userInfo.lessDeptId
          this.dataForm.createDeptName = this.userInfo.lessDeptName
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            getObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data.data
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit() {
        for (let i = 0; i < this.dataForm.detailList.length; i++) {
          if (!this.dataForm.detailList[i].invoiceTicket) {
            this.$message.warning("请先填写来票号!")
            return
          }
          if (!this.dataForm.detailList[i].costPrice) {
            this.$message.warning("请先填写成本合计!")
            return
          }
          if (!this.dataForm.detailList[i].taxPrice) {
            this.$message.warning("请先填写税额合计!")
            return
          }
          if (!this.dataForm.detailList[i].allPrice) {
            this.$message.warning("请先填写价税合计!")
            return
          }
        }
        this.ischeck = true
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.id) {
              putObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('修改成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            } else {
              addObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('添加成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            }
          } else {
            this.ischeck = false
          }
        })
      },
      //显示当前时间（年月日时分秒）
      timeFormate(timeStamp) {
        let year = new Date(timeStamp).getFullYear();
        let month =
          new Date(timeStamp).getMonth() + 1 < 10 ?
          "0" + (new Date(timeStamp).getMonth() + 1) :
          new Date(timeStamp).getMonth() + 1;
        let date =
          new Date(timeStamp).getDate() < 10 ?
          "0" + new Date(timeStamp).getDate() :
          new Date(timeStamp).getDate();
        let hh =
          new Date(timeStamp).getHours() < 10 ?
          "0" + new Date(timeStamp).getHours() :
          new Date(timeStamp).getHours();
        let mm =
          new Date(timeStamp).getMinutes() < 10 ?
          "0" + new Date(timeStamp).getMinutes() :
          new Date(timeStamp).getMinutes();
        let ss =
          new Date(timeStamp).getSeconds() < 10 ?
          "0" + new Date(timeStamp).getSeconds() :
          new Date(timeStamp).getSeconds();
        this.nowTime =
          "POUT" +
          year +
          "" +
          month +
          "" +
          date +
          "" +
          hh +
          "" +
          mm +
          "" +
          ss +
          this.dataForm.deptId;
        this.dataForm.createTime = year + "-" + month + "-" + date + " " + hh + ":" + mm + ":" + ss;
      },
      //  查询制造商信息
      supplySearchHandle() {
        this.supplyVisible = true
        this.$nextTick(() => {
          this.$refs.supplyDialog.init({})
        })
      },
      //  获取制造商信息
      getSupplyData(data) {
        this.$set(this.dataForm, 'supplyId', data.id)
        this.$set(this.dataForm, 'supplyName', data.name)
      },
      // 获取部门列表
      getDeptList() {
        getDeptInfo().then(response => {
          if(response.data.code == '0'){
            this.deptOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 选择事件 得到选中的数据
      handleSelectionChange(data) {
        this.selectlistRow = data
      },
      addRow() {
        var timestamp = new Date().getTime()
        var list = {
          timestamp: timestamp,
          invoiceTicket: '',
          costPrice: '0.00',
          taxPrice: '0.00',
          allPrice: '0.00'
        };
        this.dataForm.detailList.push(list)
      },
      //  删除
      delData() {
        this.selectlistRow.forEach((item, index) => {
          for (let i = 0; i < this.dataForm.detailList.length; i++) {
            if (this.dataForm.detailList[i].timestamp === item.timestamp) {
              this.dataForm.detailList.splice(i, 1)
            }
          }
          this.selectlistRow = []
        })
      },
      //  合计
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        columns.forEach((column, index) => {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            if (index == 2 || index == 3 || index == 4) {
              sums[index] = '合计： ' + values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0)
            }
          }
        });
        return sums;
      },
    }
  }
</script>
<style lang="scss" scoped>
  /deep/ .el-table {
    display: flex;
    flex-direction: column;
  }

  /deep/ .el-table__body-wrapper {
    order: 1;
  }

  /deep/ .bgChange {
    color: red !important;
  }
</style>
